<template>
    <div class="user-page art-full-height">
        <div class="tree-container" ref="containerRef">
            <div class="left-sidebar">
                <ElCard class="art-table-card" shadow="never" style="margin-top: 0">
                    <template #header>
                        <div style="display: flex; align-items: center; justify-content: space-between">
                            <ElSpace>
                                <ElButton size="small" type="primary" @click="toggleExpandAll" v-ripple>
                                    {{ expandAll ? '全部收起' : '全部展开' }}
                                </ElButton>
                            </ElSpace>
                        </div>
                    </template>
                    <ElInput v-model="filterText" placeholder="搜索部门" clearable size="small"
                        style="margin-bottom: 8px" />
                    <ElScrollbar style="height: 100%">
                        <ElTree ref="deptTreeRef" :data="deptTree" node-key="id" :props="treeProps"
                            :key="(expandAll ? 1 : 0)" :default-expand-all="expandAll"
                            :filter-node-method="filterNode as any" highlight-current @node-click="onDeptSelect">
                        </ElTree>
                    </ElScrollbar>
                </ElCard>
            </div>

            <div class="right-content art-full-height">
                <StaffSearch v-show="showSearchBar" v-model="searchForm" :departments="deptOptionsSource"
                    :thirdDepartments="thirdDeptOptionsSource" @search="handleStaffSearch" @reset="handleStaffReset" />
                <ElCard class="art-table-card" shadow="never" style="margin-top: 0">

                    <ArtTableHeader v-model:columns="columnChecks" v-model:showSearchBar="showSearchBar"
                        :loading="loading" @refresh="refreshData">
                        <template #left>
                            <ElSpace wrap>
                                <ElButton v-auth="'add'" type="primary" @click="showDialog('add')" v-ripple>新增员工
                                </ElButton>
                                <ArtExcelExport style="margin-left: 10px" :data="data" filename="员工数据" sheetName="员工列表"
                                    type="success" :headers="exportHeaders" auto-index
                                    @export-success="handleExportSuccess" @export-error="handleExportError"
                                    @export-progress="handleExportProgress">
                                    导出 Excel
                                </ArtExcelExport>
                                <ElTag type="info">当前部门: {{ currentDeptLabel || '全部' }}</ElTag>
                            </ElSpace>
                        </template>
                    </ArtTableHeader>
                    <ArtTable rowKey="id" :loading="loading" :data="data" :columns="columns" :pagination="pagination"
                        @pagination:size-change="handleSizeChange" @pagination:current-change="handleCurrentChange">
                    </ArtTable>
                    <!-- 员工新增/编辑弹窗 -->
                    <StaffDialog v-model:visible="dialogVisible" :type="dialogType" :editData="currentStaffData"
                        :departments="deptOptionsSource" :thirdDepartments="thirdDeptOptionsSource"
                        @submit="handleDialogSubmit" />
                </ElCard>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import StaffSearch from '@/views/system/staff/modules/staff-search.vue'
import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
import { useTable } from '@/composables/useTable'
import { fetchDeptTree, type DeptTreeNode } from '@/api/system/dept'
import { fetchStaffList, deleteStaff as deleteStaffApi, type StaffResponse } from '@/api/system/staff'
import StaffDialog from '@/views/system/staff/modules/staff-dialog.vue'
import { useDictStore } from '@/store/modules/dict'
import { useSystemStore } from '@/store/modules/system'

defineOptions({ name: 'StaffDeptTreeList' })

const showSearchBar = ref(false)
// 部门树相关
const deptTree = ref<DeptTreeNode[]>([])
const deptTreeRef = ref<any>(null)
const treeProps = { label: 'dept_name', children: 'children' }
const expandAll = ref(true)
const currentDeptLabel = ref<string>('')
const filterText = ref('')
const leftWidth = ref(280)
const containerRef = ref<HTMLElement | null>(null)
const dict = useDictStore()
const system = useSystemStore()

const industryOptions = computed(() => dict.getOptions('industry'))
const staffOptions = computed(() => dict.getOptions('staff'))
const supervisorOptions = computed(() => system.getSalers.filter((u) => u.is_supervisor !== 'N'))

// 导出表头：根据当前列配置生成映射
const exportHeaders = computed(() => {
    const list = (columns.value || []) as Array<{ prop?: string; label?: string }>
    const entries = list
        .filter((c) => c.prop && c.label && c.prop !== 'operation')
        .map((c) => [String(c.prop), String(c.label)])
    return Object.fromEntries(entries) as Record<string, string>
})

// 导出事件处理（简化版）
const exportProgress = ref(0)
const handleExportSuccess = (filename: string, rowCount: number) => {
    ElMessage.success(`成功导出 ${rowCount} 条数据`)
}
const handleExportError = (error: any) => {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
}
const handleExportProgress = (progress: number) => {
    exportProgress.value = progress
}


// 搜索表单
const searchForm = ref<Record<string, any>>({
    name: undefined,
    department: undefined,
    third_department: undefined,
    type: undefined,
    pm: undefined,
    status: undefined,
    supervisor: undefined,
    industry: undefined,
    keyword: undefined
})

const {
    data,
    columns,
    columnChecks,
    loading,
    pagination,
    refreshData,
    handleSizeChange,
    handleCurrentChange,
    searchParams,
    getData
} = useTable({
    core: {
        apiFn: fetchStaffList,
        apiParams: {
            current: 1,
            size: 20
        },
        immediate: false,
        columnsFactory: () => [
            { prop: 'id', label: 'ID', width: 80, checked: false },
            { prop: 'name', label: '姓名' },
            {
                prop: 'department', label: '事业部',
                formatter: (row) => {
                    const opt = system.getDepartments.find((op: any) => op.dept_code === (row as any).department)
                    return opt?.dept_name
                }
            },
            {
                prop: 'type', label: '类型', formatter: (row) => {
                    const opt = staffOptions.value.find((op: any) => op.value === (row as any).type)
                    return opt?.label
                }
            },
            {
                prop: 'pm', label: 'PM', width: 80, checked: false
            },
            {
                prop: 'supervisor', label: '主管',
                formatter: (row) => {
                    const opt = supervisorOptions.value.find((op: any) => op.id === (row as any).supervisor)
                    return opt?.name || (row as any).supervisor || ''
                }
            },
            { prop: 'is_supervisor', label: '主管否', width: 100, checked: false },
            {
                prop: 'third_department', label: '三级部门',
                formatter: (row) => {
                    const opt = system.getDepartments.find((op: any) => op.dept_code === (row as any).third_department)
                    return opt?.dept_name
                }
            },
            {
                prop: 'industry', label: '行业', formatter: (row) => {
                    const opt = industryOptions.value.find((op) => op.value === (row as any).industry)
                    return opt?.label || (row as any).industry || ''
                }
            },
            { prop: 'create_time', label: '创建时间' },
            {
                prop: 'operation', label: '操作', aglin: 'right',
                width: 120,
                formatter: (row) =>
                    h('div', [
                        h(ArtButtonTable, {
                            type: 'edit',
                            onClick: () => showDialog('edit', row)
                        }),
                        h(ArtButtonTable, {
                            type: 'delete',
                            onClick: () => deleteStaff(row)
                        }),
                    ])
            }
        ]
    }
})

// 展开/收起所有部门树
const toggleExpandAll = () => {
    expandAll.value = !expandAll.value
}

// 部门选择联动员工列表
const onDeptSelect = (node: DeptTreeNode) => {
    currentDeptLabel.value = node.dept_name
    const params = searchParams as Record<string, any>
    // 叶子节点：按三级部门筛选；非叶子：按事业部编码筛选
    if (!node.children || node.children.length === 0) {
        params.third_department = node.dept_code
        delete params.department
    } else {
        params.department = node.dept_code
        delete params.third_department
    }
    // 搜索并重置到第一页
    getData()
}

// 加载部门树
onMounted(async () => {
    try {
        const res = await fetchDeptTree()
        deptTree.value = res.items || []
        // 初始加载员工数据
        getData()
    } catch (error) {
        console.error('加载部门树失败:', error)
    }
})

// 树过滤：根据输入内容匹配部门名称
const filterNode = (value: string, data: DeptTreeNode) => {
    if (!value) return true
    return (data.dept_name || '').toLowerCase().includes(value.toLowerCase())
}

// 监听搜索框内容变更，触发树过滤
watch(filterText, (val) => {
    deptTreeRef.value?.filter(val)
})

// 生成部门下拉选项（所有节点）与三级部门选项（叶子节点）
const flattenDeptNodes = (nodes: DeptTreeNode[]): DeptTreeNode[] => {
    const result: DeptTreeNode[] = []
    const stack = [...nodes]
    while (stack.length) {
        const node = stack.pop() as DeptTreeNode
        result.push(node)
        if (node.children && node.children.length) {
            stack.push(...node.children)
        }
    }
    return result
}

const deptOptionsSource = computed(() => flattenDeptNodes(deptTree.value).map(n => ({
    dept_code: n.dept_code,
    dept_name: n.dept_name
})))

const thirdDeptOptionsSource = computed(() => flattenDeptNodes(deptTree.value)
    .filter(n => !n.children || n.children.length === 0)
    .map(n => ({
        dept_code: n.dept_code,
        dept_name: n.dept_name
    })))

// 处理搜索与重置
const handleStaffSearch = (params: Record<string, any>) => {
    const keys = ['name', 'department', 'type', 'pm', 'status', 'supervisor', 'is_supervisor', 'third_department', 'industry', 'keyword']
    const sp = searchParams as Record<string, any>
    keys.forEach(k => { sp[k] = params[k] ?? undefined })
    searchParams.current = 1
    getData()
}

const handleStaffReset = () => {
    const keys = ['name', 'department', 'type', 'pm', 'status', 'supervisor', 'is_supervisor', 'third_department', 'industry', 'keyword']
    const sp = searchParams as Record<string, any>
    keys.forEach(k => { delete sp[k] })
    searchParams.current = 1
    getData()
}

// 弹窗相关
const dialogType = ref<'add' | 'edit'>('add')
const dialogVisible = ref(false)
const currentStaffData = ref<Partial<StaffResponse>>({})

const showDialog = (type: 'add' | 'edit', row?: StaffResponse) => {
    dialogType.value = type
    currentStaffData.value = row || {}
    nextTick(() => {
        dialogVisible.value = true
    })
}

const handleDialogSubmit = async () => {
    dialogVisible.value = false
    currentStaffData.value = {}
    refreshData()
}

const deleteStaff = async (row: StaffResponse): Promise<void> => {
    try {
        await ElMessageBox.confirm(`确定要删除该员工吗？`, '删除员工', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        if (!row?.id) {
            ElMessage.error('缺少员工ID，无法删除')
            return
        }

        await deleteStaffApi(Number(row.id))
        ElMessage.success('删除成功')
        refreshData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    }
}


</script>

<style lang="scss" scoped>
.tree-container {
    box-sizing: border-box;
    display: flex;
    gap: 16px;
    height: 100%;
}

.left-sidebar {
    flex-shrink: 0;
    width: v-bind('leftWidth + "px"');
    height: 100%;
}

.right-content {
    flex-grow: 1;
    min-width: 0;
    height: 100%;
}

.art-table-card {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.resizer {
    flex-shrink: 0;
    width: 6px;
    cursor: col-resize;
    border-left: 1px solid var(--art-card-border);
    border-right: 1px solid var(--art-card-border);
}

@media screen and (max-width: $device-ipad) {
    .tree-container {
        display: block;
        gap: 0;
        height: auto;

        .left-sidebar {
            width: 100% !important;
            height: auto;
            margin-bottom: 20px;
        }

        .resizer {
            display: none;
        }
    }
}
</style>
